import SwiftUI
import ProgressIndicatorView

struct ProgressNcdView: View {
    
    var auto: Bool
    @State private var show: Bool = true
    @State var progress: CGFloat = 0
    @State private var timer: Timer?

    var body: some View {
        VStack(alignment: .leading, spacing: 8.0) {
            Text("加载中...")
                .font(.alibabaPuHuiTi(size: 18.0, weight: .medium))
            ProgressIndicatorView(isVisible: $show, type: .bar(progress: $progress, backgroundColor: .fsFFFFFF))
                .frame(height: 12.0)
                .foregroundColor(.fs191919)
        }
        .padding(16.0)
        .background(.fs9C9C9C)
        .clipShape(RoundedRectangle(cornerRadius: 20.0))
        .padding(.horizontal, 64.0)
        .onAppear {
            if auto {
                startLoading()
            }
        }
        .onDisappear {
            if auto {
                stopLoading()
            }
        }
    }

    private func startLoading() {
        timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
            withAnimation {
                if progress < 1.0 {
                    progress += 0.05
                } else {
                    stopLoading()
                }
            }
        }
    }

    private func stopLoading() {
        timer?.invalidate()
        timer = nil
    }
}

#Preview {
    ProgressNcdView(auto: true)
}
